package com.example.module_motocircle.motocircle

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import androidx.paging.filter
import com.example.lib_common.base.BaseViewModel
import com.example.lib_common.base.state.Empty
import com.example.lib_common.base.state.Failed
import com.example.lib_common.base.state.Loading
import com.example.lib_common.base.state.RequestEvent
import com.example.lib_common.base.state.Success
import com.example.module_motocircle.model.CommentRecord
import com.example.module_motocircle.model.DetailModel
import com.example.module_motocircle.model.NavigationItemModelItem
import com.example.module_motocircle.model.PostItem
import com.example.module_motocircle.model.SearchModelItem
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.zip
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MotocircleViewModel @Inject constructor(private val repository: MotocircleRepository) :BaseViewModel() {
    private val _navigationState = MutableStateFlow<RequestEvent>(Loading)
    val navigationState get() = _navigationState.asStateFlow()
    val mNavigationItem = mutableListOf<NavigationItemModelItem>()
    /**
     * 获得帖子数据
     * stateFlow:是一种特殊的sharedFlow,具有粘性 replay = 1，必须有初始值（sharedFlow默认0）
     */

    private val mPostState_ = MutableStateFlow<RequestEvent>(Loading)
    val mPostState = mPostState_.asStateFlow()
    var mPostListData = listOf<PostItem>()

    /**
     * 查看是否有关注
     */
    val  mCheckIfHasFocus  by lazy{
        MutableLiveData<Boolean>()
    }
    fun getNavigationItem() {
        execute(action = repository.getNavigationItem(), onStart = {
            _navigationState.emit(Loading)
        }, onError = {
            _navigationState.emit(Failed(it))
        }, onFinish = {
            it.data?.forEach { series ->

                if (!series.modelList.isNullOrEmpty()) {
                    val sb = StringBuilder()
                    series.modelList.forEach { sb.append(it.modelId).append(",") }
//                    val seriesId = sb.toString().substring(0, sb.length - 1)
//                    //系列为拼接所有车型id
//                    series.seriesId = seriesId
//                    series.modelList.add(
//                        0, ModelItem(true, name = series.value, checked = true, modelId = series.navigationId)
//                    )
                }
            }
            if (mNavigationItem == it.data && mNavigationItem.isNotEmpty()) {
                return@execute
            }
            mNavigationItem.clear()
            mNavigationItem.addAll(it.data ?: emptyList())
            _navigationState.emit(Success)
        })
    }
    //分页参数
    private var sortBy: String? = null
    private var keyword: String? = null
    private var memberId: String? = null
    private var ifFocus: Int? = null
    private var topicId : String? = null

    private var pageNum = 1
    private var pageSize = 10

    fun setPageParam(
        sortBy: String?,
        keyword: String?,
        memberId: String?,
        ifFocus: Int?,
        topicId: String?
    ) {
        this.sortBy = sortBy
        this.keyword = keyword
        this.memberId = memberId
        this.ifFocus = ifFocus
        this.topicId = topicId
    }
    /**
     * 帖子列表
     */
    fun pageList(){
        execute(
            action =  repository.pageList(sortBy, topicId, memberId, ifFocus, pageNum, pageSize, keyword),
            onStart = {
                mPostState_.value = Loading
            },
            onFinish = {
                if(it.data.records.isNullOrEmpty()){//空数据
                    mPostState_.value = Empty
                }else{
                    mPostListData = it.data.records!! //先数据后状态
                    mPostState_.value = Success
                }
            },
            onError = {
                mPostState_.value = Failed(it)
            }
        )
    }

    private val _removePostItemFlow = MutableStateFlow(mutableListOf<PostItem>())
    private val removePostItemFlow: Flow<MutableList<PostItem>> get() = _removePostItemFlow
    val postPageEvent2
        get() =
            repository.queryPostPage(
                sortType = sortBy,
                isFocus = ifFocus,
                keyword = keyword,
                memberId = memberId,
                topicId = topicId
            )
                .cachedIn(viewModelScope)
                .combine(removePostItemFlow) { data, removed ->
                    data.filter {
                        !removed.any { remove -> remove.posts_id == it.posts_id }
                    }
                }
                .shareIn(viewModelScope, SharingStarted.Lazily)

    /**
     * 是否有人关注你
     */
    fun checkIfHasFocus(){
        execute(
            action =  repository.checkIfHasFocus(),
            onError = {
                mCheckIfHasFocus.value = false
            },
            onFinish = {
                mCheckIfHasFocus.value = it.data
            }
        )
    }
    /**
     * 点赞和取消点赞帖子
     */
    private val requestLikeEvent = MutableSharedFlow<Int>()//下标
    val _requestLikeEvent = requestLikeEvent.asSharedFlow()
    fun giveLike(postsId:String,position:Int){
        execute(
            action = repository.giveLike(postsId),
            onFinish = {
                if (it.data){
                   requestLikeEvent.emit(position)
                }else{
                    requestLikeEvent.emit(-1)
                }
            },
            onError = {
                requestLikeEvent.emit(-1)
            }
        )
    }
    //搜索关键词
    val mKeywords = MutableStateFlow("")
    var mSuggestionList = mutableListOf<SearchModelItem>()
    fun clearKeyword() {
        mKeywords.value = ""
    }

    private val _searchSuggestionEvent = MutableStateFlow<RequestEvent>(Loading)
    val mSearchSuggestionEvent = _searchSuggestionEvent.asStateFlow()
    @FlowPreview
    fun getSearchKeywordList() {
        viewModelScope.launch {
            mKeywords.debounce(500)
                .filter { it.isNotBlank() }
                .collectLatest {
                    execute(action = repository.searchKeywordList(it),
                        onStart = {
                            _searchSuggestionEvent.value = Loading
                        },
                        onFinish = { model ->
                            if (!model.data.isNullOrEmpty()) {
                                mSuggestionList.clear()
                                mSuggestionList.addAll(model.data!!)
                                _searchSuggestionEvent.value = Success
                            } else {
                                mSuggestionList.clear()
                                _searchSuggestionEvent.value = Failed("暂无数据内容")
                            }
                        },
                        onError = { msg ->
                            _searchSuggestionEvent.value = Failed(msg)
                        })
                }
        }
    }
    //初始化状态
    val initState = MutableStateFlow<RequestEvent?>(Loading)

    //刷新状态
    val refreshState = MutableSharedFlow<Boolean>()


    val editCommentsFlow = MutableStateFlow("")


    val showAllCommentsFlow = MutableSharedFlow<List<Int>>()

    //当前已请求的post
    var currentPost: DetailModel? = null

    //当前已请求的comments
    var currentCommentsList: MutableList<CommentRecord> = mutableListOf()
    var formatCommentsList: MutableList<CommentRecord> = mutableListOf()
    private var currentPage = 1
    private var defaultPageSize = 10
    //记录第一页当前展开的一级评论
    val needExpendComment = mutableListOf<String>()
    fun initOrRefreshPostDetailsPageData(refreshAllComments: Boolean = false){
        val originalSize = formatCommentsList.size
        viewModelScope.launch {
            repository.getDetailInfo()
                .zip(
                    repository.getCommentInfo(currentPage,defaultPageSize)
                ){post,comments->
                    currentPost = post.data
                    currentCommentsList = comments.data.records as MutableList<CommentRecord>
                    Log.d("viewModel", "initOrRefreshPostDetailsPageData: $post")
                    Log.d("viewModel", "initOrRefreshPostDetailsPageData: $comments")
                    formatCommentsList.clear()
                    //处理获取到的评论数据
                    formatComments(currentCommentsList)
//                    needRefresh = originalSize != formatCommentsList.size
                    post
                }.handleApiException2Model()
                .collect{
                    initState.emit(Success)
                    Log.d("viewModel", "initOrRefreshPostDetailsPageData: $it")
                }
        }
    }
    private fun formatComments(it: List<CommentRecord>) {
        it.forEach {
            formatCommentsList.add(it)
            it.isFirstLevel = true
            if (it.twoLevel?.isNotEmpty() == true) {
                if (needExpendComment.any { commentId -> commentId == it.posts_comment_id }) {
                    //需要展开
                    it.twoLevel.forEachIndexed { index, replyComments ->
                        replyComments.isFirstLevel = false
                        if (index == 0) {
//                            replyComments.topRound = true
                        } else if (index > 0 && index < it.twoLevel.size - 1) {
//                            replyComments.rect = true
                        } else {
//                            replyComments.bottomRound = true
                        }
//                        replyComments.twoLevelSize = 0
                    }
                    formatCommentsList.addAll(it.twoLevel)
                } else {
                    //折叠情况
                    val replyComments = it.twoLevel[0]
//                    replyComments.twoLevelSize = it.twoLevel.size
                    replyComments.isFirstLevel = false
                    formatCommentsList.add(replyComments)
                }

            }
        }
    }
    //是否是刷新页面
    private fun isRefresh(): Boolean {
        return initState.value == Success
    }
    fun get1stPageCommentsNum(): Int {
        var size = 0
        currentCommentsList.filterIndexed { index, _ -> index < defaultPageSize }.forEach {
            size++
            size += it.twoLevel?.size ?: 0
        }
        return size
    }
}